<template>
  <div style="margin-top: 10px" class="app-contain">
    <el-row :gutter="50">
      <el-col :span="7">
        <el-card>
          <div slot="header" class="clearfix">
            <span>个人信息</span>
          </div>
          <el-row style="text-align: center">
            <el-upload
              action="/api/student/upload/image"
              accept=".jpg,.png"
              :show-file-list="false"
              :on-success="uploadSuccess"
            >
              <el-avatar
                class="el-dropdown-avatar"
                :size="100"
                :src="
                  userInfoForm.imagePath === null
                    ? require('@/assets/avatar.png')
                    : userInfoForm.imagePath
                "
              ></el-avatar>
            </el-upload>
          </el-row>
          <el-row class="user-info-userName">
            <label>{{ userInfoForm.userName }}</label>
          </el-row>
          <el-divider />
          <el-row class="user-info-fullInfo">
            <label>姓名：{{ userInfoForm.realName }}</label
            ><br />
            <label>年级：{{ levelFormatter(userInfoForm.userLevel) }}</label
            ><br />
            <label>注册时间：{{ userInfoForm.createTime }}</label
            ><br />
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="17">
        <el-card shadow="hover">
          <el-tabs active-name="event" type="card">
            <el-tab-pane label="用户动态" name="event">
              <div class="block">
                <el-timeline>
                  <el-timeline-item
                    :timestamp="item.createTime"
                    placement="top"
                    :key="item.id"
                    v-for="item in event"
                  >
                    <el-card>
                      <p>{{ item.content }}</p>
                    </el-card>
                  </el-timeline-item>
                </el-timeline>
              </div>
            </el-tab-pane>
            <el-tab-pane label="个人资料修改" name="update">
              <el-form
                :model="form"
                ref="form"
                label-width="100px"
                v-loading="formLoading"
                :rules="rules"
              >
                <el-form-item label="真实姓名：" prop="realName" required>
                  <el-input v-model="form.realName"></el-input>
                </el-form-item>
                <el-form-item label="年龄：">
                  <el-input v-model="form.age"></el-input>
                </el-form-item>
                <el-form-item label="性别：">
                  <el-select v-model="form.sex" placeholder="性别" clearable>
                    <el-option
                      v-for="item in sexEnum"
                      :key="item.key"
                      :value="item.key"
                      :label="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="出生日期：">
                  <el-date-picker
                    v-model="form.birthDay"
                    value-format="yyyy-MM-dd"
                    type="date"
                    placeholder="选择日期"
                  />
                </el-form-item>
                <el-form-item label="手机：">
                  <el-input v-model="form.phone"></el-input>
                </el-form-item>
                <el-form-item label="年级：" prop="userLevel" required>
                  <el-select v-model="form.userLevel" placeholder="年级">
                    <el-option
                      v-for="item in levelEnum"
                      :key="item.key"
                      :value="item.key"
                      :label="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="邮箱：" prop="email">
                  <el-input v-model="form.email"></el-input>
                </el-form-item>
                <el-form-item label="验证码：">
                  <el-input
                    style="width: 30%"
                    ref="code"
                    v-model="form.code"
                    placeholder="验证码"
                    name="code"
                    type="text"
                    tabindex="4"
                  />
                  <el-button
                    type="primary"
                    plain
                    :disabled="!dydShow"
                    @click="codeClick"
                    style="margin-left: 5px"
                  >
                    获取验证码
                    <span v-if="!dydShow">({{ codeTimer }}s)</span>
                  </el-button>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitForm">更新</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import userApi from "@/api/user";
import { mapGetters, mapState } from "vuex";

export default {
  data() {
    return {
      event: [],
      codeTimer: "",
      dydShow: true,
      userInfoForm: {
        userName: "",
        realName: "",
        userLevel: null,
        imagePath: null,
        createTime: null
      },
      form: {
        userName: "",
        realName: "",
        age: "",
        sex: "",
        birthDay: null,
        phone: null,
        userLevel: null,
        createTime: null,
        imagePath: null,
        email: "",
        code: "",
      },
      formLoading: false,
      rules: {
        realName: [
          { required: true, message: "请输入真实姓名", trigger: "blur" },
        ],
        userLevel: [
          { required: true, message: "请选择年级", trigger: "change" },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          {
            validator: function (rule, value, callback) {
              var reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
              if (reg.test(value) == false) {
                callback(new Error("邮箱格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    let _this = this;
    userApi.getUserEvent().then((re) => {
      _this.event = re.response;
    });
    userApi.getCurrentUser().then((re) => {
      _this.form = JSON.parse(JSON.stringify(re.response));
      _this.userInfoForm = re.response;
    });
    this.codeTimer = window.localStorage.getItem("changeCodeTime");
    if (this.codeTimer && this.codeTimer > 0) {
      this.dydShow = false;
      this.timer = setInterval(() => {
        if (
          window.localStorage.getItem("changeCodeTime") > 0 &&
          window.localStorage.getItem("changeCodeTime") <= 60
        ) {
          window.localStorage.setItem(
            "changeCodeTime",
            window.localStorage.getItem("changeCodeTime") - 1
          );
          this.codeTimer = window.localStorage.getItem("changeCodeTime");
        } else {
          this.dydShow = true;
          clearInterval(this.timer); // 清除定时器
          window.localStorage.removeItem("changeCodeTime");
        }
      }, 1000);
    }
  },
  methods: {
    codeClick() {
      if (!window.localStorage.getItem("changeCodeTime")) {
        let _this = this;
        this.$refs.form.validate((valid) => {
          if (valid) {
            userApi
              .sendCode({ email: this.form.email })
              .then(function (result) {
                if (result && result.code === 1) {
                  _this.$message({
                    message: "发送邮件成功",
                    type: "success",
                  });
                } else {
                  _this.loading = false;
                  _this.$message.error(result.message);
                }
              })
              .catch(function (reason) {});
            this.codeTimer = 60;
            // 判断时间是不是要显示
            this.dydShow = false;
            window.localStorage.setItem("changeCodeTime", 60);
            // 设置倒计时定时器
            this.timer = setInterval(() => {
              if (
                window.localStorage.getItem("changeCodeTime") > 0 &&
                window.localStorage.getItem("changeCodeTime") <= 60
              ) {
                window.localStorage.setItem(
                  "changeCodeTime",
                  window.localStorage.getItem("changeCodeTime") - 1
                );
                this.codeTimer = window.localStorage.getItem("changeCodeTime");
              } else {
                this.dydShow = true;
                clearInterval(this.timer); // 清除定时器
                window.localStorage.removeItem("changeCodeTime");
              }
            }, 1000);
          } else {
            return false;
          }
        });
      }
    },
    uploadSuccess(re, file) {
      if (re.code === 1) {
        window.location.reload();
        this.$message.success("修改头像成功");
      } else {
        this.$message.error(re.message);
      }
    },
    submitForm() {
      let _this = this;
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.formLoading = true;
          userApi
            .update(this.form)
            .then((data) => {
              if (data.code === 1) {
                _this.$message.success(data.message);
              } else {
                _this.$message.error(data.message);
              }
              _this.formLoading = false;
            })
            .catch((e) => {
              _this.formLoading = false;
            });
        } else {
          return false;
        }
      });
    },
    levelFormatter(level) {
      return this.enumFormat(this.levelEnum, level);
    },
  },
  computed: {
    ...mapGetters("enumItem", ["enumFormat"]),
    ...mapState("enumItem", {
      sexEnum: (state) => state.user.sexEnum,
      levelEnum: (state) => state.user.levelEnum,
    }),
  },
};
</script>

<style lang="scss" scoped>
</style>
